package com.sinochem.sales.gateway.service.impl;

import com.sinochem.sales.gateway.service.PermissionService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xuan😴🐶🐱🐽🌺  <a href="zhangshixuanj@163.com">联系作者</a>
 * @version Revision:v1.0,Date: 2018/4/18 13:54
 * @project parent
 * @description 权限
 * @Modification Date: 2018/4/18 13:54  {填写修改说明}
 */
@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private PathMatcher pathMatcher;

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
        boolean hasPermission = false;

        if (principal != null) {
            if (null != grantedAuthorityList || grantedAuthorityList.isEmpty()) {
                return true;
            }

            Set<String> urls = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.toSet());

            for (String url : urls) {
                if (StringUtils.isNotEmpty(url) && antPathMatcher.match(url, request.getRequestURI())
                        && request.getMethod().equalsIgnoreCase(url)) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}
